<script setup lang="ts">
import { ref, reactive, onMounted, h } from "vue";
import { router } from "@/router";
import {
  getIpSegmentWeights,
  calculateIpSegmentWeights,
  getDepartmentIpDistribution,
} from "../servers";
import { message } from "@/utils/message";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { DynamicTableInstance } from "@/components/DynamicTable/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import { ElMessage, ElMessageBox } from "element-plus";

const props = defineProps<{
  task: string;
}>();

defineOptions({
  name: "IpWeight",
});

// 表单引用
const searchFormRef = ref<DynamicFormInstance>();
const tableRef = ref<DynamicTableInstance>();

// 表格数据
const tableData = ref([]);
const loading = ref(false);

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  pageSizes: [10, 20, 50],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

// 搜索表单数据
const searchFormData = reactive({
  department: "",
});

// 搜索表单配置
const searchFormConfig: FormItemConfig[] = [
  {
    type: "input",
    key: "department",
    name: "部门名称",
    placeholder: "请输入部门名称",
    params: {
      clearable: true,
    },
  },
];

// 表格列配置
const tableColumns: TableColumn[] = [
  {
    label: "IP段",
    prop: "ip_segment",
    show: true,
    showOverflowTooltip: true,
  },
  {
    label: "权重(IP数量)",
    prop: "weight",
    show: true,
  },
  {
    label: "涉及部门",
    prop: "departments",
    show: true,
    slot: "departments",
  },
  {
    label: "部门权重分布",
    prop: "department_weights",
    show: true,
    slot: "department_weights",
  },
  {
    label: "更新时间",
    prop: "updated_at",
    show: true,
  },
];

// 获取IP段权重列表
const getIpSegmentWeightsList = async () => {
  loading.value = true;
  try {
    const res = await getIpSegmentWeights({
      department: searchFormData.department || undefined,
      page: pagination.currentPage,
      per_page: pagination.pageSize,
    });

    if (res.code === 2000) {
      tableData.value = res.data.segments || [];
      pagination.total = res.data.total || 0;
    }
  } catch (error) {
    console.error("获取IP段权重列表失败:", error);
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = (value: any) => {
  searchFormData.department = value.department || "";
  pagination.currentPage = 1;
  getIpSegmentWeightsList();
};

// 重置搜索
const handleSearchReset = () => {
  searchFormRef.value?.resetFields();
  searchFormData.department = "";
  pagination.currentPage = 1;
  getIpSegmentWeightsList();
};

// 手动触发权重计算
const handleCalculateWeights = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要重新计算IP段权重吗？这可能需要几分钟时间。",
      "确认计算",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const res = await calculateIpSegmentWeights();
    if (res.code === 2000) {
      ElMessage.success("权重计算任务已启动，请稍后刷新查看结果");
    } else {
      ElMessage.error("启动计算任务失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("触发计算失败:", error);
      ElMessage.error("触发计算失败");
    }
  }
};

// 分页处理
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  getIpSegmentWeightsList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  getIpSegmentWeightsList();
};

// 解析部门列表
const parseDepartments = (departments: any) => {
  if (!departments) {
    return [];
  }

  // 如果已经是数组，直接返回
  if (Array.isArray(departments)) {
    return departments;
  }

  // 如果是字符串，尝试解析JSON
  if (typeof departments === "string") {
    try {
      const parsed = JSON.parse(departments);
      return Array.isArray(parsed) ? parsed : [parsed];
    } catch {
      return [departments];
    }
  }

  return [];
};

// 解析部门权重分布
const parseDepartmentWeights = (departmentWeights: any) => {
  if (!departmentWeights) {
    return {};
  }

  // 如果已经是对象，直接返回
  if (
    typeof departmentWeights === "object" &&
    !Array.isArray(departmentWeights)
  ) {
    return departmentWeights;
  }

  // 如果是字符串，尝试解析JSON
  if (typeof departmentWeights === "string") {
    try {
      return JSON.parse(departmentWeights);
    } catch {
      return {};
    }
  }

  return {};
};

// 格式化部门名称
const formatDepartmentName = (deptName: string) => {
  // 检查参数是否有效
  if (!deptName || typeof deptName !== "string") {
    return "未知部门";
  }

  // 显示完整的部门层级路径
  return deptName;
};

// 生命周期
onMounted(() => {
  getIpSegmentWeightsList();
});
</script>

<template>
  <div>
    <!-- 搜索表单 -->
    <el-card shadow="never">
      <div class="search-form-container">
        <DynamicForm
          ref="searchFormRef"
          v-model="searchFormData"
          :form-config="searchFormConfig"
          :gutter="16"
          label-width="80px"
          type="search"
          @search="handleSearch"
          @reset="handleSearchReset"
        />
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="mt-4">
      <DynamicTable
        ref="tableRef"
        :data="tableData"
        :columns="tableColumns"
        :loading="loading"
        :pagination="pagination"
        :showToolbar="true"
        border
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <template #toolbar-left>
          <el-button type="primary" @click="handleCalculateWeights">
            重新计算权重
          </el-button>
        </template>

        <!-- 涉及部门列插槽 -->
        <template #departments="{ row }">
          <div class="departments-list">
            <div
              v-for="(dept, index) in parseDepartments(row.departments)"
              :key="index"
              class="department-item"
              :title="dept"
            >
              <div class="dept-path">
                <span
                  v-for="(part, partIndex) in String(dept).split('/')"
                  :key="partIndex"
                  class="dept-level"
                  :class="{
                    'dept-level-last':
                      partIndex === String(dept).split('/').length - 1,
                  }"
                >
                  {{ part }}
                </span>
              </div>
            </div>
          </div>
        </template>

        <!-- 部门权重分布列插槽 -->
        <template #department_weights="{ row }">
          <div class="weights-distribution">
            <div
              v-for="(count, dept) in parseDepartmentWeights(
                row.department_weights
              )"
              :key="dept"
              class="weight-item"
            >
              <div class="dept-path">
                <span
                  v-for="(part, partIndex) in String(dept).split('/')"
                  :key="partIndex"
                  class="dept-level"
                  :class="{
                    'dept-level-last':
                      partIndex === String(dept).split('/').length - 1,
                  }"
                >
                  {{ part }}
                </span>
              </div>
              <el-tag type="info" size="small" class="weight-tag">{{
                String(count)
              }}</el-tag>
            </div>
          </div>
        </template>
      </DynamicTable>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-card__header) {
}

:deep(.el-pagination) {
  justify-content: right;
  margin-top: 10px;
  margin-right: 30px;
}

.search-form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.departments-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-width: 100%;
}

.department-item {
  padding: 6px 8px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #409eff;
  transition: all 0.2s ease;
}

.department-item:hover {
  background: #e6f7ff;
  border-left-color: #1890ff;
}

.dept-path {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 4px;
}

.dept-level {
  font-size: 12px;
  color: #606266;
  padding: 2px 4px;
  border-radius: 3px;
  background: #fff;
  border: 1px solid #e4e7ed;
  transition: all 0.2s ease;
}

.dept-level-last {
  color: #409eff;
  font-weight: 500;
  background: #e6f7ff;
  border-color: #91d5ff;
}

.dept-separator {
  color: #c0c4cc;
  font-weight: bold;
  margin: 0 2px;
}

.weights-distribution {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.weight-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 8px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #67c23a;
  transition: all 0.2s ease;
}

.weight-item:hover {
  background: #f0f9ff;
  border-left-color: #52c41a;
}

.weight-tag {
  flex-shrink: 0;
  min-width: 50px;
  text-align: center;
  font-weight: 600;
}

.el-btn-zese {
  background: #722ed1;
  color: white;
  border-color: #722ed1;
}

.el-btn-zese.is-disabled,
.el-btn-zese.is-disabled:focus,
.el-btn-zese.is-disabled:hover {
  background: #722ed1;
  color: white;
  border-color: #722ed1;
}
</style>
